<script lang="ts">
  import { onMount } from "svelte";
  import { Button } from "$lib/components/ui/button";
  import ReportForm from "$lib/components/ReportForm.svelte";
  import ReportList from "$lib/components/ReportList.svelte";
  import ReportPreview from "$lib/components/ReportPreview.svelte";
  import SettingsPage from "$lib/components/SettingsPage.svelte";
  import WeeklyConversionNotice from "$lib/components/WeeklyConversionNotice.svelte";
  import { isEditing, reports, isLoading, reportActions, currentReport, settings } from "$lib/store";
  import { FileText, List, Eye, Settings, Plus } from "lucide-svelte";
  import { invoke } from '@tauri-apps/api/core';

  let currentView = $state<'form' | 'list' | 'preview' | 'settings'>('form');
  let showWeeklyNotice = $state(false);
  let hasUnconvertedPlan = $state(false);

  // 应用启动时加载数据
  onMount(async () => {
    await reportActions.loadReports();
    await checkWeeklyConversion();
  });

  // 检查是否需要显示周计划转换提醒
  async function checkWeeklyConversion() {
    try {
      const currentSettings = $settings;
      if (!currentSettings.showWeeklyNotice) {
        return;
      }

      const shouldConvert = await invoke<boolean>('should_convert_to_weekly');
      if (shouldConvert) {
        // 检查是否有未转换的明日计划
        const reportsData = $reports;
        const todayReport = reportsData.find(r => {
          const today = new Date().toLocaleDateString('zh-CN');
          return r.date.includes(today.split('/')[1]) && r.date.includes(today.split('/')[2]);
        });
        
        if (todayReport && todayReport.tomorrowPlan && !todayReport.weekPlan) {
          hasUnconvertedPlan = true;
          showWeeklyNotice = true;
        }
      }
    } catch (error) {
      console.error('检查周计划转换失败:', error);
    }
  }

  function handleConvertToWeekly() {
    // 这里可以触发当前报告的转换
    showWeeklyNotice = false;
    // 如果当前在表单页面，可以直接转换
    if (currentView === 'form' && $currentReport) {
      // 触发表单中的转换逻辑
    }
  }

  function dismissWeeklyNotice() {
    showWeeklyNotice = false;
  }

  function switchToForm() {
    currentView = 'form';
    reportActions.setCurrentReport(null);
    reportActions.setEditing(false);
  }

  function switchToList() {
    currentView = 'list';
  }

  function switchToPreview() {
    currentView = 'preview';
  }

  function switchToSettings() {
    currentView = 'settings';
  }

  function getViewTitle() {
    switch (currentView) {
      case 'form': return $isEditing ? '编辑日报' : '新建日报';
      case 'list': return '日报列表';
      case 'preview': return '日报预览';
      case 'settings': return '设置';
      default: return '日报小程序';
    }
  }
</script>

<main class="min-h-screen bg-notion-bg">
  <!-- 极简头部导航 -->
  <header class="bg-notion-bg border-b border-notion-border">
    <div class="max-w-6xl mx-auto px-6 py-3">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <h1 class="text-lg font-medium text-notion-text">📝 日报</h1>
          <span class="text-sm text-notion-text-secondary">
            {getViewTitle()}
          </span>
        </div>
        
        <div class="flex items-center space-x-1">
          <button 
            onclick={switchToForm}
            class={`px-3 py-1.5 text-sm rounded transition-colors duration-100 flex items-center gap-1.5 notion-hover ${
              currentView === 'form' 
                ? 'bg-notion-bg-selected text-notion-text' 
                : 'text-notion-text-secondary hover:text-notion-text'
            }`}
          >
            {#if currentView === 'form'}
              <FileText class="w-3.5 h-3.5" />
            {:else}
              <Plus class="w-3.5 h-3.5" />
            {/if}
            {$isEditing ? '编辑' : '新建'}
          </button>
          
          <button 
            onclick={switchToList}
            class={`px-3 py-1.5 text-sm rounded transition-colors duration-100 flex items-center gap-1.5 notion-hover ${
              currentView === 'list' 
                ? 'bg-notion-bg-selected text-notion-text' 
                : 'text-notion-text-secondary hover:text-notion-text'
            }`}
          >
            <List class="w-3.5 h-3.5" />
            列表 ({$reports.length})
          </button>

          {#if $currentReport && currentView !== 'preview'}
            <button 
              onclick={switchToPreview}
              class="px-3 py-1.5 text-sm rounded transition-colors duration-100 flex items-center gap-1.5 text-notion-text-secondary hover:text-notion-text notion-hover"
            >
              <Eye class="w-3.5 h-3.5" />
              预览
            </button>
          {/if}
          
          <button 
            onclick={switchToSettings}
            class={`px-3 py-1.5 text-sm rounded transition-colors duration-100 flex items-center gap-1.5 notion-hover ${
              currentView === 'settings' 
                ? 'bg-notion-bg-selected text-notion-text' 
                : 'text-notion-text-secondary hover:text-notion-text'
            }`}
          >
            <Settings class="w-3.5 h-3.5" />
            设置
          </button>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区域 -->
  <div class="max-w-6xl mx-auto px-6 py-6">
    {#if $isLoading}
      <div class="flex items-center justify-center py-16">
        <div class="text-center">
          <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-notion-text-secondary mx-auto mb-3"></div>
          <p class="text-notion-text-secondary text-sm">加载中...</p>
        </div>
      </div>
    {:else if currentView === 'form'}
      <ReportForm />
    {:else if currentView === 'list'}
      <ReportList />
    {:else if currentView === 'preview' && $currentReport}
      <ReportPreview report={$currentReport} />
    {:else if currentView === 'settings'}
      <SettingsPage />
    {:else}
      <div class="text-center py-16">
        <p class="text-notion-text-secondary">请选择一个功能开始使用</p>
      </div>
    {/if}
  </div>

  <!-- 周计划转换通知 -->
  <WeeklyConversionNotice 
    show={showWeeklyNotice}
    onConvert={handleConvertToWeekly}
    onDismiss={dismissWeeklyNotice}
  />
</main>
